package command;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Invoker {

	List<Command> commands;

	public List<Command> getCommands() {
		return commands;
	}

	Command undoCommand;

	public Invoker() {
		commands = new ArrayList<Command>();
		clearCommands();
	}

	public void addCommand(Command cmd) {
		commands.add(cmd);
	}

	public void executeLastCommand() {
		Command cmd = commands.get(commands.size() - 1);
		cmd.execute();
		undoCommand = cmd;
	}

	public void undoLastCommand() {
		undoCommand.undo();
		commands.remove(undoCommand);
		if (!commands.isEmpty())
			undoCommand = commands.get(commands.size() - 1);
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Number of commands: " + commands.size());
		return sb.toString();
	}

	public void clearCommands() {
		commands.clear();
	}

	public void undoAllCommands() {
		Collections.reverse(commands);
		for (Command cmd : commands) {
			cmd.undo();
		}
		clearCommands();
	}

	public void removeCurrentCommand() {
		commands.remove(undoCommand);
	}
}
